package io.sage.modules.sys.controller;

import java.util.*;
import java.util.stream.Collectors;

import io.sage.modules.query.entity.BAreaConfig;
import io.sage.modules.query.service.BAreaConfigService;
import io.sage.modules.sys.entity.SysUserEntity;
import io.sage.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.sage.common.utils.Constant;
import io.sage.common.utils.R;
import io.sage.common.utils.RedisUtils;
import io.sage.modules.sys.entity.SysDeptEntity;
import io.sage.modules.sys.service.SysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


/**
 * 部门管理
 * 
 */
@RestController
@RequestMapping("/sys/dept")
@Api(tags="系统部门接口")
public class SysDeptController extends AbstractController {
	@Autowired
	private SysDeptService sysDeptService;
	
	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private BAreaConfigService bAreaConfigService;
	
	/**
	 * 部门列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:dept:list")
	@ApiOperation("部门列表")
	public List<SysDeptEntity> list(){
//		List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<String, Object>());
		List<SysDeptEntity> deptList = sysDeptService.queryList1(new HashMap<String, Object>());

		return deptList;
	}
	/**
	 * 部门列表
	 */
	@RequestMapping("/listByUser")
	@ApiOperation("部门列表 根据当前用户的部门id进行过滤")
	public List<SysDeptEntity> listByUser(){
		Map map=new HashMap<String, Object>();
		SysUserEntity user = ShiroUtils.getUserEntity();
		map.put("deptId",user.getDeptId());
//		List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<String, Object>());
		List<SysDeptEntity> deptList = sysDeptService.queryListByUser(map);

		return deptList;
	}

	/**
	 * 选择部门(添加、修改菜单)
	 */
	@RequestMapping("/select")
	@RequiresPermissions("sys:dept:select")
	public R select(){
		List<SysDeptEntity> deptList = sysDeptService.queryList1(new HashMap<String, Object>());

		//添加一级部门
		if(getUserId() == Constant.SUPER_ADMIN){
			SysDeptEntity root = new SysDeptEntity();
			root.setDeptId(0L);
			root.setName("一级部门");
			root.setParentId(-1L);
			root.setOpen(true);
			deptList.add(root);
		}

		return R.ok().put("deptList", deptList);
	}

	/**
	 * 上级部门Id(管理员则为0)
	 */
	@RequestMapping("/info")
	@RequiresPermissions("sys:dept:list")
	public R info(){
		long deptId = 0;
		if(getUserId() != Constant.SUPER_ADMIN){
			List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<String, Object>());
			Long parentId = null;
			for(SysDeptEntity sysDeptEntity : deptList){
				if(parentId == null){
					parentId = sysDeptEntity.getParentId();
					continue;
				}

				if(parentId > sysDeptEntity.getParentId().longValue()){
					parentId = sysDeptEntity.getParentId();
				}
			}
			deptId = parentId;
		}

		return R.ok().put("deptId", deptId);
	}
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{deptId}")
	@RequiresPermissions("sys:dept:info")
	public R info(@PathVariable("deptId") Long deptId){
		SysDeptEntity dept = sysDeptService.selectById(deptId);

		BAreaConfig areaConfig=new BAreaConfig();
		areaConfig.setDeptId(deptId.intValue());
		List<BAreaConfig> list=bAreaConfigService.queryAll(areaConfig);
		if(list.size()>0){
			dept.setLatitude(list.get(0).getLatitude());
			dept.setLongitude(list.get(0).getLongitude());
		}
		return R.ok().put("dept", dept);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("sys:dept:save")
	public R save(@RequestBody SysDeptEntity dept){
		//获取父id
		Long parentId = dept.getParentId();
		//根据父id查询父的数据信息.
		SysDeptEntity deptParent = sysDeptService.selectById(parentId);
		Integer deptLength = null;
		if(deptParent.getLeve()==1){
			dept.setLeve(2);
			deptLength=4;
		}else if(deptParent.getLeve()==2){
			dept.setLeve(3);
			deptLength=6;
		}else if(deptParent.getLeve()==3){
			dept.setLeve(4);
			deptLength=8;
		}else {
			return R.error("父部门没有等级，请检查父部门数据.");
		}
		
		//获取到父亲的deptNo
		String deptNo = deptParent.getDeptNo();//  01  02  03
		String maxNo = "";
			if(StringUtils.isNotBlank(deptNo)){
				List<SysDeptEntity> deptList = sysDeptService.getDeptList(deptNo, deptLength);
				if(deptList.size()>0){
					maxNo = deptList.get(0).getDeptNo();
					Integer serialNoMax = Integer.valueOf(maxNo);
					Integer serialNoMaxs = serialNoMax+1;
					String string = serialNoMaxs.toString();
					string = "0"+string;
					dept.setDeptNo(string);
				}else{ 
					dept.setDeptNo(deptNo+"01");//  "0101"
				}
				
			}
		
		boolean insert = sysDeptService.insert(dept);
		dept=sysDeptService.getDeptByNo(dept.getDeptNo());
		bAreaConfigService.deleteByDeptId(dept.getDeptId());
		BAreaConfig bAreaConfig=new BAreaConfig();
		bAreaConfig.setIsDel(0);
		bAreaConfig.setLatitude(dept.getLatitude());
		bAreaConfig.setLongitude(dept.getLongitude());
		bAreaConfig.setDeptId(dept.getDeptId().intValue());
		bAreaConfig.setCreateId(ShiroUtils.getUserId().intValue());
		bAreaConfig.setCreateTime(new Date());
		bAreaConfigService.insert(bAreaConfig);

		if(insert){
			redisUtils.delete("deptList");
			return R.ok();
		}
		
		return R.error("失败");
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("sys:dept:update")
	public R update(@RequestBody SysDeptEntity dept){
		
		boolean state = sysDeptService.updateById(dept);
		if(state){
			redisUtils.delete("deptList");
			bAreaConfigService.deleteByDeptId(dept.getDeptId());
			BAreaConfig bAreaConfig=new BAreaConfig();
			bAreaConfig.setIsDel(0);
			bAreaConfig.setLatitude(dept.getLatitude());
			bAreaConfig.setLongitude(dept.getLongitude());
			bAreaConfig.setDeptId(dept.getDeptId().intValue());
			bAreaConfig.setCreateId(ShiroUtils.getUserId().intValue());
			bAreaConfig.setCreateTime(new Date());
			bAreaConfigService.insert(bAreaConfig);

			return R.ok();
		}
		
		return R.error("失败");
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:dept:delete")
	public R delete(long deptId){
		//判断是否有子部门
		List<Long> deptList = sysDeptService.queryDetpIdList(deptId);
		if(deptList.size() > 0){
			return R.error("请先删除子部门");
		}

		boolean state = sysDeptService.deleteById(deptId);
		
		if(state){
			redisUtils.delete("deptList");
			return R.ok();
		}
		
		return R.error("失败");
	}
	/**
	 * 删除
	 */
	@GetMapping("/getDeptTree")
	public R getDeptTree(){
		Map map=new HashMap<String, Object>();
		SysUserEntity user = ShiroUtils.getUserEntity();
		//map.put("parentId",user.getDeptId());
//		List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<String, Object>());
		List<SysDeptEntity> deptList = sysDeptService.queryList1(map);
		Collections.sort(deptList);
		Map<Long, List<SysDeptEntity>> mapList = deptList.parallelStream().collect(Collectors.groupingBy(SysDeptEntity::getParentId));
		Map<Long, List<SysDeptEntity>> mapLists = deptList.parallelStream().collect(Collectors.groupingBy(SysDeptEntity::getDeptId));
		List<SysDeptEntity> list=mapLists.get(user.getDeptId());
		for (int i = 0; i < list.size(); i++){
			list.set(i,this.getChildren(list.get(i),mapList));
		}

		return R.ok().put("data",list);
	}

	public SysDeptEntity getChildren(SysDeptEntity sysDeptEntity,Map<Long, List<SysDeptEntity>> map){
		sysDeptEntity.setList((List<SysDeptEntity>)map.get(sysDeptEntity.getDeptId()));
		if(sysDeptEntity.getList() ==null ){
			return sysDeptEntity;
		}
		for (int i = 0; i < sysDeptEntity.getList().size(); i++) {
			SysDeptEntity sysDeptEntity1=sysDeptEntity.getList().get(i);
			sysDeptEntity.getList().set(i,this.getChildren(sysDeptEntity1,map));
		}
		return sysDeptEntity;
	}

}
